import {patch, cascade, fetch} from '../../../utils/axios'

const state = {
  name: '新增服务',
  type: {},
  status: {},
  fields: {},
  env: {},
  OutterIpSource: {},
  host: {items: [{ text: '', value: '' }]},
  tempEnv: '',
  valid: null,
  nameRules: [
    (v) => !!v || '请输入服务名'
  ],
  innerIpRules: [
    (v) => !!v || '请输入内网地址'
  ],
  typeRules: [
    (v) => !!v || '请输选择类型'
  ],
  statusRules: [
    (v) => v !== undefined || '请输选择状态'
  ],
  envRules: [
    (v) => !!v || '请输选择环境'
  ],
  msg: {
    innerIp: ''
  }
}

const mutations = {
  editService (state, payload) {
    if (payload.validate()) {
      var url = '/service/' + state.fields.id + '/'
      patch(url,
        state.fields
      ).then((response) => {
        this._vm.$data.$$state.listservice.editdialog = false
      }).catch((error) => {
        if (error.response) {
          let datas = error.response.data
          for (var name in datas) {
            state.msg[name] = datas[name]
          }
        }
      })
    }
  },
  deleteService (state) {
    let r = confirm('确认删除？')
    if (r === true) {
      var url = '/service/' + state.fields.id + '/'
      cascade(url).then((response) => {
        this._vm.$data.$$state.listservice.editdialog = false
      }).catch((error) => {
        console.log(error.response.data.detail)
      })
    }
  },
  closeEditService (state) {
    this._vm.$data.$$state.listservice.editdialog = false
    let msg = this.msg
    for (var i in msg) {
      msg[i] = ''
    }
  },
  loadEditService (state, payload) {
    let url = '/service/' + payload + '/'
    fetch(url, {
    }).then((response) => {
      state.fields = response
      state.tempEnv = state.fields.env
    }).catch((error) => {
      alert(error.response)
    })
    state.type = this._vm.$data.$$state.listservice.type
    state.status = this._vm.$data.$$state.listservice.status
    state.env = this._vm.$data.$$state.listservice.env
    state.OutterIpSource = this._vm.$data.$$state.listservice.OutterIpSource
  },
  serviceEditEnv (state) {
    if (state.tempEnv !== state.fields.env) {
      state.fields.host = []
    }
    state.host = {items: [{ text: '', value: '' }]}
    fetch('/service/get_host/', {
      env: state.fields.env
    }).then((response) => {
      let res = JSON.parse(response)
      state.host.items = res.host
    }).catch((error) => {
      state.etext = error.response
    })
  }
}

const actions = {
  editService ({commit, state}, payload) {
    commit('editService', payload)
  },
  deleteService ({commit}) {
    commit('deleteService')
  },
  closeEditService ({commit}) {
    commit('closeEditService')
  },
  loadEditService ({commit}, payload) {
    commit('loadEditService', payload)
  },
  serviceEditEnv ({commit}) {
    commit('serviceEditEnv')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
